package com.example.backend.controller;

import com.example.backend.entity.Admin;
import com.example.backend.entity.Rider;
import com.example.backend.service.RiderService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
@Log4j
public class RiderController{
    @Autowired
    private RiderService riderService;

    @PostMapping("/rider/login")
    public Map<String, Object> doLogin(@RequestBody Rider rider) {
        Map<String, Object> result = new HashMap<>();
        try {
            Rider loginRider = riderService.selectRider(rider);

            if (loginRider != null) {
                if(loginRider.getState().equals("待认证")){
                    result.put("success", false);
                    result.put("message", "骑手待认证");
                }
                else{
                    String token = UUID.randomUUID().toString().replace("-", "");
                    result.put("success", true);
                    result.put("rider", loginRider);
                    result.put("token", token);
                    result.put("message", "登录成功");

                }
            } else {
                result.put("success", false);
                result.put("message", "用户名或密码错误");
            }

        } catch (Exception e) {
            log.error("登录异常", e);
            result.put("success", false);
            result.put("message", "服务器内部错误");
        }
        return result;
    }

    @PostMapping("/rider")
    public int doRegister(@RequestBody Rider rider) {
        return riderService.addRider(rider);
    }

    @PutMapping("/rider")
    public int doUpdate(@RequestBody Rider rider) {
        return riderService.updateRider(rider);
    }

    @DeleteMapping("/rider/{riderId}")
    public int doDelete(@PathVariable("riderId") String id) {
        return riderService.deleteRiderById(id);
    }

   @GetMapping("/rider/list")
    public Map<String, Object> doList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize,
            Rider rider) {

        return riderService.selectRiders(rider, pageNum, pageSize);
    }

    @GetMapping("/rider/{id}")
    public Rider getRiderById(@PathVariable("id") String id) {
        return riderService.selectRiderById(id);
    }

    @PutMapping("/rider/score/{id}")
    public int updateRiderScore(@PathVariable("id") Integer id) {
        return riderService.updateRiderScore(id);
    }
}
